<?php
namespace Report\Controller;
use Think\Controller;
class CommissionController extends Controller {
    public function rebateLog(){//1-返佣记录,2-外佣记录
        $status=I('status') ? I('status') : 0;
        $login=I('id') ? I('id') : 0;
        $from=I('from') ? strtotime(I('from')) : 0;
        $to=I('to') ? strtotime(I('to').' 23:59:59') : 0;
        $type=I('type') ? I('type') : 1;
        $where='(type='.$type.') ';
        if(!empty($status)){
            if($status==1){
                $where.=' and (code = 1) ';
            }else{
                $where.=' and (code <> 1) ';
            }
            $this->assign('status',$status);
        }
        if(!empty($login)){
            $where.=' and (payee='.$login.') ';
            $this->assign('id',$login);
        }
        if(!empty($from) && !empty($to)){
            $where.=' and (time between '.$from.' and '.$to.') ';
            $this->assign('from',I('from'));
            $this->assign('to',I('to'));
        }
        $model = M('rebate_log');
        $count = $model->where($where)->count();
        $Page = new \Think\Page($count,20);
        $Page->parameter['status']=$status;
        $Page->parameter['id']=$login;
        $Page->parameter['type']=$type;
        $Page->parameter['from']=I('from');
        $Page->parameter['to']=I('to');
        $show = $Page->show();
        $list = $model->field('id,order_num,code,money,payee,time,from,to,type')
            ->where($where)->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        //查看今天是否有返佣
        $y = date("Y");
        $m = date("m");
        $d = date("d");
        $time=mktime(0,0,0,$m,$d,$y);
        //var_dump(date("Y-m-d h:is",$time));die;
        $return_operation_log=M('return_operation_log')->where(['time'=>$time,'type'=>$type])->find();
        $this->assign('return_operation_log',$return_operation_log);
        $this->assign('list',$list);
        $this->assign('page',$show);
        $this->assign('type',$type);
        $this->display();
    }

    public function downloadRebateLog(){
        $status=I('status') ? I('status') : 0;
        $login=I('id') ? I('id') : 0;
        $from=I('from') ? strtotime(I('from')) : 0;
        $to=I('to') ? strtotime(I('to').' 23:59:59') : 0;
        $type=I('type') ? I('type') : 1;
        $where='(type='.$type.') ';
        if(!empty($status)){
            if($status==1){
                $where.=' and (code = 1) ';
            }else{
                $where.=' and (code <> 1) ';
            }
            $this->assign('status',$status);
        }
        if(!empty($login)){
            $where.=' and (payee='.$login.') ';
        }
        if(!empty($from) && !empty($to)){
            $where.=' and (time between '.$from.' and '.$to.') ';
        }
        $list = M('rebate_log')->field('order_num,payee,code,money,time,from,to,type')->where($where)->select();
        $data=[];
        foreach ($list as $k => $v){
            $data[]=array(
                'order_num'=>$v['order_num'],
                'payee'=>$v['payee'],
                'code'=>$v['code']==1 ? '成功' : '失败',
                'money'=>$v['money'],
                'time'=>date('Y-m-d H:i:s',$v['time']),
                'date'=>date('Y-m-d H:i:s',$v['from']).' -- '.date('Y-m-d H:i:s',$v['to']),
                'type'=>$v['type']==1 ? '返佣' : '外佣'
            );
        }
        $csv=new \Think\Csv();
        $csv_title=array('交易号','收佣账户','状态码','佣金金额','发放时间','日期范围','类型');
        $csv->put_csv($data,$csv_title);
    }

    public function getRebate($arr,$agent){//获取返佣数据的父级
        foreach($arr as $k => $v){
            if($v['user_id']==$agent){
                if($v['position']==1){
                    return $this->getRebate($arr,$v['user_recommend']);
                }else{
                    return array('user_id'=>$v['user_id'],'group'=>$v['group'],'position'=>$v['position']);
                }
            }
        }
    }

    public function rebate(){//返佣-一层
        $admin = session('report');
        $y = date("Y");
        $m = date("m");
        $d = date("d");
        $from = mktime(0, 0, 0, $m, $d, $y) - (24 * 60 * 60)+1;
        $to = mktime(0, 0, 0, $m, $d, $y);
		
		//echo date('Y-m-d H:i:s',$from).'**************'.date('Y-m-d H:i:s',$to);die;
        if(empty($admin['user_id'])){
            $this->ajaxReturn(array('msg'=>'登录已失效，请重新登录','status'=>0));
        }
        //返佣点击记录
        $click_log['admin_id'] = $admin['user_id'];
        $click_log['time'] = time();
        $click_log['type'] = 1;
        $click_res=M('rebate_click_log')->add($click_log);//$click_res=1;
        if($click_res){
            $return_operation_log_model = M('return_operation_log');//查询当天是否有返佣
            $has = $return_operation_log_model->where(['time'=>$to,'type'=>1])->find();
            if(empty($has)){
                $userAll=M('user')->field('user_id,user_recommend,group,position')->where('user_role=1')->select();
                $logins=[];//
                $allUser=[];
                foreach($userAll as $k => $v){
                    $logins[]=$v['user_id'];
                    $allUser[$v['user_id']]=$v;
                }
                $reoups=M('mt4_trades','','DB_CONFIG2')->field('LOGIN,sum(VOLUME)')
                    ->where('(CMD between 0 and 1) and (CLOSE_TIME between \''.date('Y-m-d H:i:s',$from).'\' and \''.date('Y-m-d H:i:s',$to).'\') and (right(SYMBOL,2) = \'bo\')')
                    ->group('LOGIN')->select();
                foreach ($reoups as $k => $v){
                    if(!in_array($v['login'],$logins)){
                        unset($reoups[$k]);
                    }
                }
                $reoups=array_merge($reoups);
                if(empty($reoups)){
                    $this->ajaxReturn(array('msg'=>'未找到交易记录','status'=>0));
                }
                $group=M('mt4_groups')->field('mt4_group,ratio')->select();
                $ratio=[];//每个组别的佣金比率
                foreach ($group as $k => $v){
                    $ratio[$v['mt4_group']]=$v['ratio'];
                }
                $parent=[];//可以得到佣金的账户
                $rebateData=[];//最终需要返佣的数据
                foreach ($reoups as $k => $v){//获取自己的佣金返给谁
                    if(!empty($allUser[$v['login']]) && ($allUser[$v['login']]['user_recommend']!=0)){
                        $v['ratio']=$ratio[$allUser[$v['login']]['group']];
                        $v['parent']=$this->getRebate($userAll,$allUser[$v['login']]['user_recommend']);
                        if(!empty($v['parent'])){//剔除没有父级的数据，防止无用循环
                            $v['money']=round($ratio[$v['parent']['group']]*round($v['sum(volume)']/100),2);
                            if($v['money']!=0){$rebateData[]=$v;$parent[]=$v['parent']['user_id'];}//剔除金额为0的数据，防止无用循环
                        }
                    }
                    /*foreach ($userAll as $ke => $va){
                        if($v['login']==$va['user_id']){
                            $v['ratio']=$ratio[$va['group']];
                            $v['parent']=$this->getRebate($userAll,$va['user_recommend']);
                            if(!empty($v['parent'])){//剔除没有父级的数据，防止无用循环
                                $v['money']=round($ratio[$v['parent']['group']]*round($v['sum(volume)']/100),2);
                                if($v['money']!=0){$rebateData[]=$v;$parent[]=$v['parent']['user_id'];}//剔除金额为0的数据，防止无用循环
                            }
                            break;
                        }
                    }*/
                }
                //print_r($rebateData);die;
                $parent=array_unique($parent);
                $parent=array_merge($parent);
                $finalData=[];
                foreach($parent as $k => $v){
                    $money=0;
                    foreach ($rebateData as $ke => $va){
                        if($v==$va['parent']['user_id']){
                            $money+=$va['money'];
                        }
                    }
                    $finalData[]=array('login'=>$v,'money'=>$money);
                }
                //print_r($finalData);die;
                $rebate_data=[];
                foreach ($finalData as $k => $v){
                    if($v['money']!=0){
                        $request = "action=changebalance&login=".$v['login']."&value=".$v['money']."&comment=CommBo".date("Ymd",strtotime("-1 day"))."\0";
                        $return = mt4_operation($request);
                        parse_str($return,$res);
                        $rebate_data[]=array(
                            'code'=>$res['result'],//状态码
                            'money'=>$v['money'],// 发放的佣金金额
                            'time'=>time(),//发放时间
                            'payee'=>$v['login'],//收款人
                            'from'=>$from,
                            'to'=>$to,
                            'type'=>1,
                            'order_num'=>$res['order']//订单号
                        );
                    }
                }
                $res1=M('rebate_log')->addAll($rebate_data);//将佣金发放信息存入数据库
                if($res1){//将操作记录写入数据库
                    $return_operation_log['admin_id'] = $admin['user_id'];
                    $return_operation_log['time'] = $to;
                    $return_operation_log['type'] = 1;
                    $res2 = M('return_operation_log')->add($return_operation_log);
                    if ($res2) {
                        $this->ajaxReturn(array('msg' => '操作成功', 'status' => 1));
                    } else {
                        $this->ajaxReturn(array('msg' => '佣金发放成功，操作记录未保存成功', 'status' => -1));
                    }
                }else{
                    $this->ajaxReturn(array('msg'=>'佣金发放成功，记录保存失败','status'=>-1));
                }
            }else{
                $this->ajaxReturn(array('msg'=>'今日佣金已发放','status'=>0));
            }
        }else{
            $this->ajaxReturn(array('msg'=>'操作失败，请重试','status'=>0));
        }
    }

    public function rebate_test(){//返佣-一层
        $admin = session('report');
        $y = date("Y");
        $m = date("m");
        $d = date("d");
        $from = mktime(0, 0, 0, $m, $d, $y) - (24 * 60 * 60)+1;
        $to = mktime(0, 0, 0, $m, $d, $y);

        //echo date('Y-m-d H:i:s',$from).'**************'.date('Y-m-d H:i:s',$to);die;
        /*if(empty($admin['user_id'])){
            $this->ajaxReturn(array('msg'=>'登录已失效，请重新登录','status'=>0));
        }
        //返佣点击记录
        $click_log['admin_id'] = $admin['user_id'];
        $click_log['time'] = time();
        $click_log['type'] = 1;
        $click_res=M('rebate_click_log')->add($click_log);*/$click_res=1;
        if($click_res){
            $return_operation_log_model = M('return_operation_log');//查询当天是否有返佣
            $has = $return_operation_log_model->where(['time'=>$to,'type'=>1])->find();
            if(empty($has)){
                $userAll=M('user')->field('user_id,user_recommend,group,position')->where('user_role=1')->select();
                $logins=[];//
                $allUser=[];
                foreach($userAll as $k => $v){
                    $logins[]=$v['user_id'];
                    $allUser[$v['user_id']]=$v;
                }
                $reoups=M('mt4_trades','','DB_CONFIG2')->field('LOGIN,sum(VOLUME)')
                    ->where('(CMD between 0 and 1) and (CLOSE_TIME between \''.date('Y-m-d H:i:s',$from).'\' and \''.date('Y-m-d H:i:s',$to).'\') and (right(SYMBOL,2) = \'bo\')')
                    ->group('LOGIN')->select();
                foreach ($reoups as $k => $v){
                    if(!in_array($v['login'],$logins)){
                        unset($reoups[$k]);
                    }
                }
                $reoups=array_merge($reoups);
                if(empty($reoups)){
                    //$this->ajaxReturn(array('msg'=>'','status'=>0));
					die('未找到交易记录');
                }
                $group=M('mt4_groups')->field('mt4_group,ratio')->select();
                $ratio=[];//每个组别的佣金比率
                foreach ($group as $k => $v){
                    $ratio[$v['mt4_group']]=$v['ratio'];
                }
                $parent=[];//可以得到佣金的账户
                $rebateData=[];//最终需要返佣的数据
                foreach ($reoups as $k => $v){//获取自己的佣金返给谁
                    if(!empty($allUser[$v['login']]) && ($allUser[$v['login']]['user_recommend']!=0)){
                        $v['ratio']=$ratio[$allUser[$v['login']]['group']];
                        $v['parent']=$this->getRebate($userAll,$allUser[$v['login']]['user_recommend']);
                        if(!empty($v['parent'])){//剔除没有父级的数据，防止无用循环
                            $v['money']=round($ratio[$v['parent']['group']]*round($v['sum(volume)']/100),2);
                            if($v['money']!=0){$rebateData[]=$v;$parent[]=$v['parent']['user_id'];}//剔除金额为0的数据，防止无用循环
                        }
                    }
                    /*foreach ($userAll as $ke => $va){
                        if($v['login']==$va['user_id']){
                            $v['ratio']=$ratio[$va['group']];
                            $v['parent']=$this->getRebate($userAll,$va['user_recommend']);
                            if(!empty($v['parent'])){//剔除没有父级的数据，防止无用循环
                                $v['money']=round($ratio[$v['parent']['group']]*round($v['sum(volume)']/100),2);
                                if($v['money']!=0){$rebateData[]=$v;$parent[]=$v['parent']['user_id'];}//剔除金额为0的数据，防止无用循环
                            }
                            break;
                        }
                    }*/
                }
                //print_r($rebateData);die;
                $parent=array_unique($parent);
                $parent=array_merge($parent);
                $finalData=[];
                foreach($parent as $k => $v){
                    $money=0;
                    foreach ($rebateData as $ke => $va){
                        if($v==$va['parent']['user_id']){
                            $money+=$va['money'];
                        }
                    }
                    $finalData[]=array('login'=>$v,'money'=>$money);
                }
                print_r($finalData);die;
                foreach ($finalData as $k => $v){
                    if($v['money']!=0){
                        $request = "action=changebalance&login=".$v['login']."&value=".$v['money']."&comment=CommBo".date("Ymd",strtotime("-1 day"))."\0";
                        $return = mt4_operation($request);
                        parse_str($return,$res);
                        $rebate_data[]=array(
                            'code'=>$res['result'],//状态码
                            'money'=>$v['money'],// 发放的佣金金额
                            'time'=>time(),//发放时间
                            'payee'=>$v['login'],//收款人
                            'from'=>$from,
                            'to'=>$to,
                            'type'=>1,
                            'order_num'=>$res['order']//订单号
                        );
                    }
                }
                $res1=M('rebate_log')->addAll($rebate_data);//将佣金发放信息存入数据库
                if($res1){//将操作记录写入数据库
                    $return_operation_log['admin_id'] = $admin['user_id'];
                    $return_operation_log['time'] = $to;
                    $return_operation_log['type'] = 1;
                    $res2 = M('return_operation_log')->add($return_operation_log);
                    if ($res2) {
                        $this->ajaxReturn(array('msg' => '操作成功', 'status' => 1));
                    } else {
                        $this->ajaxReturn(array('msg' => '佣金发放成功，操作记录未保存成功', 'status' => -1));
                    }
                }else{
                    $this->ajaxReturn(array('msg'=>'佣金发放成功，记录保存失败','status'=>-1));
                }
            }else{
                $this->ajaxReturn(array('msg'=>'今日佣金已发放','status'=>0));
            }
        }else{
            $this->ajaxReturn(array('msg'=>'操作失败，请重试','status'=>0));
        }
    }

    public function getRebateParents($data,$user_recommend,$position,$arr){//获取IB返佣数据的父级
        foreach($data as $k => $v){
            if($v['user_id']==$user_recommend){
                if($v['position']>1){
                    if($v['position']>=$position){
                        $arr[]=array('user_id'=>$v['user_id'],'position'=>$v['position']);
                        unset($data[$k]);
                        $arr=$this->getRebateParents($data,$v['user_recommend'],$v['position'],$arr);
                    }else{
                        unset($data[$k]);
                        $arr=$this->getRebateParents($data,$v['user_recommend'],$position,$arr);
                    }
                }else{
                    unset($data[$k]);
                    $arr=$this->getRebateParents($data,$v['user_recommend'],$position,$arr);
                }
            }
        }
        return $arr;
    }

    public function rebate2(){//多层返佣
        $admin = session('report');
        $y = date("Y");
        $m = date("m");
        $d = date("d");
        $from = mktime(0, 0, 0, $m, $d, $y) - 16*(24 * 60 * 60)+1;
        $to = mktime(0, 0, 0, $m, $d, $y);
        /*if(empty($admin['user_id'])){
            $this->ajaxReturn(array('msg'=>'登录已失效，请重新登录','status'=>0));
        }
        //返佣点击记录
        $click_log['admin_id'] = $admin['user_id'];
        $click_log['time'] = time();
        $click_log['type'] = 1;
        $click_res=M('rebate_click_log')->add($click_log);*/
        $click_res=1;
        if($click_res){
            $return_operation_log_model = M('return_operation_log');//查询当天是否有返佣
            $has = $return_operation_log_model->where(['time'=>$to,'type'=>1])->find();
            if(empty($has)){
                $userAll=M('user')->field('user_id,user_recommend,position')->where('user_role=1')->select();
                $logins=[];//
                $allUser=[];
                foreach($userAll as $k => $v){
                    $logins[]=$v['user_id'];
                    $allUser[$v['user_id']]=$v;
                }
                $reoups=M('mt4_trades','','DB_CONFIG2')->field('LOGIN,sum(VOLUME)')
                    ->where('(CMD between 0 and 1) and (CLOSE_TIME between \''.date('Y-m-d H:i:s',$from).'\' and \''.date('Y-m-d H:i:s',$to).'\') and (right(SYMBOL,2) = \'bo\')')
                    ->group('LOGIN')->select();
                foreach ($reoups as $k => $v){
                    if(!in_array($v['login'],$logins)){
                        unset($reoups[$k]);
                    }
                }
                $reoups=array_merge($reoups);
                if(empty($reoups)){
                    $this->ajaxReturn(array('msg'=>'未找到交易记录','status'=>0));
                }
                $hasTradesUser=[];//有交易的用户信息
                foreach($reoups as $k => $v){
                    if(!empty($allUser[$v['login']]) && ($allUser[$v['login']]['user_recommend']!=0)){
                        $v['user_recommend']=$allUser[$v['login']]['user_recommend'];
                        $v['volume']=intval($v['sum(volume)']/100);
                        $v['position']=1;//将所有交易用户的position设置为1避免IB交易时无法查出他的上级
                        $hasTradesUser[]=$v;
                    }
                    /*foreach ($userAll as $ke => $va){
                        if(($v['login']==$va['user_id']) && ($va['user_recommend']!=0)){
                            $va['volume']=intval($v['sum(volume)']/100);
                            $va['position']=1;//将所有交易用户的position设置为1避免IB交易时无法查出他的上级
                            $hasTradesUser[]=$va;break;
                        }
                    }*/
                }
                $rebateLogin=[];//最终返佣的账号
                $rebateData=[];//最终需要返佣的数据-明细
                foreach ($hasTradesUser as $k => $v){
                    $parents=$this->getRebateParents($userAll,$v['user_recommend'],$v['position'],[]);
                    if(!empty($parents)){
                        $parents2=$parents;
                        foreach($parents2 as $ke => $va){
                            $flag=0;
                            foreach($parents as $key => $val){
                                if($va['position']==$val['position']){
                                    $flag++;
                                    if($flag>2){
                                        unset($parents[$key]);
                                    }
                                }
                            }
                        }
                        $v['parents']=$parents;//筛选出有返佣父级的数据
                        $rebateData[]=$v;
                        foreach ($parents as $ke => $va){
                            $rebateLogin[]=$va['user_id'];
                        }
                    }
                }
                if(empty($rebateData)){$this->ajaxReturn(array('msg'=>'今日无佣金需要发放','status'=>0));}
                $rebateLogin=array_unique($rebateLogin);
                $rebateLogin=array_merge($rebateLogin);
                $position=M('position')->field('id,ratio')->select();
                $pos=[];
                foreach($position as $k => $v){
                    $pos[$v['id']]=$v['ratio'];
                }
                foreach ($rebateData as $k => $v){
                    foreach ($v['parents'] as $ke => $va){
                        $rebateData[$k]['parents'][$ke]['ratio']=$pos[$va['position']];
                        if($ke>0){
                            $ratio=$pos[$va['position']]-$pos[$v['parents'][$ke-1]['position']];
                            if($ratio>0){
                                $rebateData[$k]['parents'][$ke]['money']=$ratio*$v['volume'];
                            }else if($ratio==0){
                                $rebateData[$k]['parents'][$ke]['money']=$rebateData[$k]['parents'][$ke-1]['money']*0.1;
                            }else{
                                $rebateData[$k]['parents'][$ke]['money']=0;
                            }
                        }else{
                            $rebateData[$k]['parents'][$ke]['money']=$pos[$va['position']]*$v['volume'];
                        }
                    }
                }
                //print_r($rebateData);die;
                $finalData=[];//最终需要发放的数据
                foreach ($rebateLogin as $k => $v){
                    $data=array('login'=>$v,'money'=>0);
                    foreach ($rebateData as $ke => $va){
                        foreach ($va['parents'] as $key => $val){
                            if($v==$val['user_id']){
                                $data['money']+=$val['money'];
                            }
                        }
                    }
                    $data['money']=round($data['money'],2);
                    $finalData[]=$data;
                }
                print_r($finalData);die;
                foreach ($finalData as $k => $v){
                    if($v['money']!=0){
                        $request = "action=changebalance&login=".$v['login']."&value=".round($v['money'], 2)."&comment=CommBo".date("Ymd",strtotime("-1 day"))."\0";
                        $return = mt4_operation($request);
                        parse_str($return,$res);
                        $rebate_data[]=array(
                            'code'=>$res['result'],//状态码
                            'money'=>round($v2['money'], 2),// 发放的佣金金额
                            'time'=>time(),//发放时间
                            'payee'=>$v['login'],//收款人
                            'from'=>$from,
                            'to'=>$to,
                            'type'=>1,
                            'order_num'=>$res['order']//订单号
                        );
                    }
                }
                $res1=M('rebate_log')->addAll($rebate_data);//将佣金发放信息存入数据库
                if($res1){//将操作记录写入数据库
                    $return_operation_log['admin_id'] = $admin['user_id'];
                    $return_operation_log['time'] = $to;
                    $return_operation_log['type'] = 1;
                    $res2 = M('return_operation_log')->add($return_operation_log);
                    if ($res2) {
                        $this->ajaxReturn(array('msg' => '操作成功', 'status' => 1));
                    } else {
                        $this->ajaxReturn(array('msg' => '佣金发放成功，操作记录未保存成功', 'status' => -1));
                    }
                }else{
                    $this->ajaxReturn(array('msg'=>'佣金发放成功，记录保存失败','status'=>-1));
                }
            }else{
                $this->ajaxReturn(array('msg'=>'今日佣金已发放','status'=>0));
            }
        }else{
            $this->ajaxReturn(array('msg'=>'操作失败，请重试','status'=>0));
        }
    }

    public function rebate3(){//返佣+外汇返佣
        $admin = session('report');
        $y = date("Y");
        $m = date("m");
        $d = date("d");
        $from = mktime(0, 0, 0, $m, $d, $y) - (24 * 60 * 60)+1;
        $to = mktime(0, 0, 0, $m, $d, $y);
        if(empty($admin['user_id'])){
            $this->ajaxReturn(array('msg'=>'登录已失效，请重新登录','status'=>0));
        }
        //返佣点击记录
        $click_log['admin_id'] = $admin['user_id'];
        $click_log['time'] = time();
        $click_log['type'] = 1;
        $click_res=M('rebate_click_log')->add($click_log);
        //$click_res=1;
        if($click_res){
            $return_operation_log_model = M('return_operation_log');//查询当天是否有返佣
            $has = $return_operation_log_model->where(['time'=>$to,'type'=>1])->find();
            if(empty($has)){
                $userAll=M('user')->field('user_id,user_recommend,position')->where('user_role=1')->select();
                $logins=[];//
                $allUser=[];
                foreach($userAll as $k => $v){
                    $logins[]=$v['user_id'];
                    $allUser[$v['user_id']]=$v;
                }
                $reoups=M('mt4_trades','','DB_CONFIG2')->field('LOGIN,SYMBOL,sum(VOLUME)')
                    ->where('(CMD between 0 and 1) and (CLOSE_TIME between \''.date('Y-m-d H:i:s',$from).'\' and \''.date('Y-m-d H:i:s',$to).'\')')
                    ->group('LOGIN,SYMBOL')->select();
                foreach ($reoups as $k => $v){
                    if(!in_array($v['login'],$logins)){
                        unset($reoups[$k]);
                    }
                }
                $reoups=array_merge($reoups);
                if(empty($reoups)){
                    $this->ajaxReturn(array('msg'=>'未找到交易记录','status'=>0));
                }
                //print_r($reoups);die;
                $hasTradesUser=[];//有交易的用户信息
                foreach($reoups as $k => $v){
                    if(!empty($allUser[$v['login']]) && ($allUser[$v['login']]['user_recommend']!=0)){
                        $v['user_recommend']=$allUser[$v['login']]['user_recommend'];
                        $v['volume']=round($v['sum(volume)']/100,2);
                        $v['position']=1;//将所有交易用户的position设置为1避免IB交易时无法查出他的上级
                        $hasTradesUser[]=$v;
                    }
                    /*foreach ($userAll as $ke => $va){
                        if(($v['login']==$va['user_id']) && ($va['user_recommend']!=0)){
                            $va['symbol']=$v['symbol'];
                            $va['volume']=round($v['sum(volume)']/100,2);
                            $va['position']=1;//将所有交易用户的position设置为1避免IB交易时无法查出他的上级
                            $hasTradesUser[]=$va;break;
                        }
                    }*/
                }
                //print_r($hasTradesUser);die;
                //品种点差
                $spreadData=M('symbol_spread')->field('id,symbol,spread')->select();
                $spread=[];
                foreach($spreadData as $k => $v){
                    $spread[$v['symbol']]=$v['spread'];
                }
                //$rebateLogin=[];//最终返佣的账号
                $rebateData=[];//最终需要返佣的数据-明细
                foreach ($hasTradesUser as $k => $v){
                    $parents=$this->getRebateParents($userAll,$v['user_recommend'],$v['position'],[]);
                    if(!empty($parents)){
                        $parents2=$parents;
                        foreach($parents2 as $ke => $va){
                            $flag=0;
                            foreach($parents as $key => $val){
                                if($va['position']==$val['position']){
                                    $flag++;
                                    if($flag>2){
                                        unset($parents[$key]);
                                    }
                                }
                            }
                        }
                        $v['spread']=$spread[$v['symbol']];
                        $v['parents']=$parents;//筛选出有返佣父级的数据
                        $rebateData[]=$v;
                        /*foreach ($parents as $ke => $va){
                            $rebateLogin[]=$va['user_id'];
                        }*/
                    }
                }
                if(empty($rebateData)){$this->ajaxReturn(array('msg'=>'今日无佣金需要发放','status'=>0));}
                /*$rebateLogin=array_unique($rebateLogin);
                $rebateLogin=array_merge($rebateLogin);*/
                $position=M('position')->field('id,ratio,ratio_foreign')->select();
                $pos=[];//返佣比率
                $foreign=[];//外用比率
                $parent_arr=[];//最终返佣的账号
                foreach($position as $k => $v){
                    $pos[$v['id']]=$v['ratio'];
                    $foreign[$v['id']]=$v['ratio_foreign'];
                }
                foreach ($rebateData as $k => $v){//计算佣金信息
                    if(substr($v['symbol'],-2)=='bo'){
                        foreach ($v['parents'] as $ke => $va){
                            $parent_arr[]=$va['user_id'];
                            $rebateData[$k]['parents'][$ke]['ratio']=$pos[$va['position']];
                            if($ke>0){
                                $ratio=$pos[$va['position']]-$pos[$v['parents'][$ke-1]['position']];
                                if($ratio>0){
                                    $rebateData[$k]['parents'][$ke]['money']=$ratio*$v['volume'];
                                }else if($ratio==0){
                                    $rebateData[$k]['parents'][$ke]['money']=$rebateData[$k]['parents'][$ke-1]['money']*0.1;
                                }else{
                                    $rebateData[$k]['parents'][$ke]['money']=0;
                                }
                            }else{
                                $rebateData[$k]['parents'][$ke]['money']=$pos[$va['position']]*$v['volume'];
                            }
                        }
                    }else{
                        foreach ($v['parents'] as $ke => $va){
                            $parent_arr[]=$va['user_id'];
                            $rebateData[$k]['parents'][$ke]['ratio']=$foreign[$va['position']];
                            if($ke>0){
                                $ratio=$foreign[$va['position']]-$foreign[$v['parents'][$ke-1]['position']];
                                if($ratio>0){
                                    $rebateData[$k]['parents'][$ke]['money']=$ratio*$v['volume']*$v['spread'];
                                }else if($ratio==0){
                                    $rebateData[$k]['parents'][$ke]['money']=$rebateData[$k]['parents'][$ke-1]['money']*0.1;
                                }else{
                                    $rebateData[$k]['parents'][$ke]['money']=0;
                                }
                            }else{
                                $rebateData[$k]['parents'][$ke]['money']=$foreign[$va['position']]*$v['volume']*$v['spread'];
                            }
                        }
                    }
                }
                //print_r($rebateData);die;
                $parent_arr=array_unique($parent_arr);
                $parent_arr=array_merge($parent_arr);
                $finalData=[];//最终需要发放的数据
                foreach($parent_arr as $k => $v){
                    $data['login']=$v;
                    $data['money']=0;
                    foreach($rebateData as $ke => $va){
                        foreach($va['parents'] as $key => $val){
                            if($v==$val['user_id']){
                                $data['money']+=$val['money'];
                            }
                        }
                    }
                    $finalData[]=$data;
                }
                //print_r($finalData);die;
                $rebate_data=[];
                foreach ($finalData as $k => $v){
                    if($v['money']!=0){
                        $request = "action=changebalance&login=".$v['login']."&value=".round($v['money'], 2)."&comment=CommBo".date("Ymd",strtotime("-1 day"))."\0";
                        $return = mt4_operation($request);
                        parse_str($return,$res);
                        $rebate_data[]=array(
                            'code'=>$res['result'],//状态码
                            'money'=>round($v['money'], 2) ? round($v['money'], 2) : 0,// 发放的佣金金额
                            'time'=>time(),//发放时间
                            'payee'=>$v['login'],//收款人
                            'from'=>$from,
                            'to'=>$to,
                            'type'=>1,
                            'order_num'=>$res['order']//订单号
                        );
                    }
                }
                $res1=M('rebate_log')->addAll($rebate_data);//将佣金发放信息存入数据库
                if($res1){//将操作记录写入数据库
                    $return_operation_log['admin_id'] = $admin['user_id'];
                    $return_operation_log['time'] = $to;
                    $return_operation_log['type'] = 1;
                    $res2 = M('return_operation_log')->add($return_operation_log);
                    if ($res2) {
                        $this->ajaxReturn(array('msg' => '操作成功', 'status' => 1));
                    } else {
                        $this->ajaxReturn(array('msg' => '佣金发放成功，操作记录未保存成功', 'status' => -1));
                    }
                }else{
                    $this->ajaxReturn(array('msg'=>'佣金发放成功，记录保存失败','status'=>-1));
                }
            }else{
                $this->ajaxReturn(array('msg'=>'今日佣金已发放','status'=>0));
            }
        }else{
            $this->ajaxReturn(array('msg'=>'操作失败，请重试','status'=>0));
        }
    }

    public function rebate3_test(){//返佣+外汇返佣
        $admin = session('report');$admin['user_id']=0;
        $y = date("Y");
        $m = date("m");
        $d = date("d");
        $from = mktime(0, 0, 0, $m, $d, $y) - (24 * 60 * 60)+1;
        $to = mktime(0, 0, 0, $m, $d, $y)+(24 * 60 * 60);
        /*if(empty($admin['user_id'])){
            $this->ajaxReturn(array('msg'=>'登录已失效，请重新登录','status'=>0));
        }
        //返佣点击记录
        $click_log['admin_id'] = $admin['user_id'];
        $click_log['time'] = time();
        $click_log['type'] = 1;
        $click_res=M('rebate_click_log')->add($click_log);*/
        $click_res=1;
        if($click_res){
            /*$return_operation_log_model = M('return_operation_log');//查询当天是否有返佣
            $has = $return_operation_log_model->where(['time'=>$to,'type'=>1])->find();*/
            if(empty($has)){
                $userAll=M('user')->field('user_id,user_recommend,position')->where('user_role=1')->select();
                $logins=[];//
                $allUser=[];
                foreach($userAll as $k => $v){
                    $logins[]=$v['user_id'];
                    $allUser[$v['user_id']]=$v;
                }
                $reoups=M('mt4_trades','','DB_CONFIG2')->field('LOGIN,SYMBOL,sum(VOLUME)')
                    ->where('(CMD between 0 and 1) and (CLOSE_TIME between \''.date('Y-m-d H:i:s',$from).'\' and \''.date('Y-m-d H:i:s',$to).'\')')
                    ->group('LOGIN,SYMBOL')->select();
                foreach ($reoups as $k => $v){
                    if(!in_array($v['login'],$logins)){
                        unset($reoups[$k]);
                    }
                }
                $reoups=array_merge($reoups);
                if(empty($reoups)){
					die('未找到交易记录');
                    $this->ajaxReturn(array('msg'=>'未找到交易记录','status'=>0));
                }
                //print_r($reoups);die;
                $hasTradesUser=[];//有交易的用户信息
                foreach($reoups as $k => $v){
                    if(!empty($allUser[$v['login']]) && ($allUser[$v['login']]['user_recommend']!=0)){
                        $v['user_recommend']=$allUser[$v['login']]['user_recommend'];
                        $v['volume']=round($v['sum(volume)']/100,2);
                        $v['position']=1;//将所有交易用户的position设置为1避免IB交易时无法查出他的上级
                        $hasTradesUser[]=$v;
                    }
                    /*foreach ($userAll as $ke => $va){
                        if(($v['login']==$va['user_id']) && ($va['user_recommend']!=0)){
                            $va['symbol']=$v['symbol'];
                            $va['volume']=round($v['sum(volume)']/100,2);
                            $va['position']=1;//将所有交易用户的position设置为1避免IB交易时无法查出他的上级
                            $hasTradesUser[]=$va;break;
                        }
                    }*/
                }
                //print_r($hasTradesUser);die;
                //品种点差
                $spreadData=M('symbol_spread')->field('id,symbol,spread')->select();
                $spread=[];
                foreach($spreadData as $k => $v){
                    $spread[$v['symbol']]=$v['spread'];
                }
                //$rebateLogin=[];//最终返佣的账号
                $rebateData=[];//最终需要返佣的数据-明细
                foreach ($hasTradesUser as $k => $v){
                    $parents=$this->getRebateParents($userAll,$v['user_recommend'],$v['position'],[]);
                    if(!empty($parents)){
                        $parents2=$parents;
                        foreach($parents2 as $ke => $va){
                            $flag=0;
                            foreach($parents as $key => $val){
                                if($va['position']==$val['position']){
                                    $flag++;
                                    if($flag>2){
                                        unset($parents[$key]);
                                    }
                                }
                            }
                        }
                        $v['spread']=$spread[$v['symbol']];
                        $v['parents']=$parents;//筛选出有返佣父级的数据
                        $rebateData[]=$v;
                        /*foreach ($parents as $ke => $va){
                            $rebateLogin[]=$va['user_id'];
                        }*/
                    }
                }
                if(empty($rebateData)){die('今日无佣金需要发放');$this->ajaxReturn(array('msg'=>'今日无佣金需要发放','status'=>0));}
                /*$rebateLogin=array_unique($rebateLogin);
                $rebateLogin=array_merge($rebateLogin);*/
                $position=M('position')->field('id,ratio,ratio_foreign')->select();
                $pos=[];//返佣比率
                $foreign=[];//外用比率
                $parent_arr=[];//最终返佣的账号
                foreach($position as $k => $v){
                    $pos[$v['id']]=$v['ratio'];
                    $foreign[$v['id']]=$v['ratio_foreign'];
                }
                foreach ($rebateData as $k => $v){//计算佣金信息
                    if(substr($v['symbol'],-2)=='bo'){
                        foreach ($v['parents'] as $ke => $va){
                            $parent_arr[]=$va['user_id'];
                            $rebateData[$k]['parents'][$ke]['ratio']=$pos[$va['position']];
                            if($ke>0){
                                $ratio=$pos[$va['position']]-$pos[$v['parents'][$ke-1]['position']];
                                if($ratio>0){
                                    $rebateData[$k]['parents'][$ke]['money']=$ratio*$v['volume'];
                                }else if($ratio==0){
                                    $rebateData[$k]['parents'][$ke]['money']=$rebateData[$k]['parents'][$ke-1]['money']*0.1;
                                }else{
                                    $rebateData[$k]['parents'][$ke]['money']=0;
                                }
                            }else{
                                $rebateData[$k]['parents'][$ke]['money']=$pos[$va['position']]*$v['volume'];
                            }
                        }
                    }else{
                        foreach ($v['parents'] as $ke => $va){
                            $parent_arr[]=$va['user_id'];
                            $rebateData[$k]['parents'][$ke]['ratio']=$foreign[$va['position']];
                            if($ke>0){
                                $ratio=$foreign[$va['position']]-$foreign[$v['parents'][$ke-1]['position']];
                                if($ratio>0){
                                    $rebateData[$k]['parents'][$ke]['money']=$ratio*$v['volume']*$v['spread'];
                                }else if($ratio==0){
                                    $rebateData[$k]['parents'][$ke]['money']=$rebateData[$k]['parents'][$ke-1]['money']*0.1;
                                }else{
                                    $rebateData[$k]['parents'][$ke]['money']=0;
                                }
                            }else{
                                $rebateData[$k]['parents'][$ke]['money']=$foreign[$va['position']]*$v['volume']*$v['spread'];
                            }
                        }
                    }
                }
                print_r($rebateData);die;
                $parent_arr=array_unique($parent_arr);
                $parent_arr=array_merge($parent_arr);
                $finalData=[];//最终需要发放的数据
                foreach($parent_arr as $k => $v){
                    $data['login']=$v;
                    $data['money']=0;
                    foreach($rebateData as $ke => $va){
                        foreach($va['parents'] as $key => $val){
                            if($v==$val['user_id']){
                                $data['money']+=$val['money'];
                            }
                        }
                    }
                    $finalData[]=$data;
                }
                print_r($finalData);die;
                foreach ($finalData as $k => $v){
                    if($v['money']!=0){
                        $request = "action=changebalance&login=".$v['login']."&value=".round($v['money'], 2)."&comment=CommBo".date("Ymd",strtotime("-1 day"))."\0";
                        $return = mt4_operation($request);
                        parse_str($return,$res);
                        $rebate_data[]=array(
                            'code'=>$res['result'],//状态码
                            'money'=>round($v['money'], 2),// 发放的佣金金额
                            'time'=>time(),//发放时间
                            'payee'=>$v['login'],//收款人
                            'from'=>$from,
                            'to'=>$to,
                            'type'=>1,
                            'order_num'=>$res['order']//订单号
                        );
                    }
                }
                $res1=M('rebate_log')->addAll($rebate_data);//将佣金发放信息存入数据库
                if($res1){//将操作记录写入数据库
                    $return_operation_log['admin_id'] = $admin['user_id'];
                    $return_operation_log['time'] = $to;
                    $return_operation_log['type'] = 1;
                    $res2 = M('return_operation_log')->add($return_operation_log);
                    if ($res2) {
                        $this->ajaxReturn(array('msg' => '操作成功', 'status' => 1));
                    } else {
                        $this->ajaxReturn(array('msg' => '佣金发放成功，操作记录未保存成功', 'status' => -1));
                    }
                }else{
                    $this->ajaxReturn(array('msg'=>'佣金发放成功，记录保存失败','status'=>-1));
                }
            }else{
                $this->ajaxReturn(array('msg'=>'今日佣金已发放','status'=>0));
            }
        }else{
            $this->ajaxReturn(array('msg'=>'操作失败，请重试','status'=>0));
        }
    }

    public function returnFDHs(){//外佣扣款
        $admin = session('report'); //当前的操作人员
        $y = date("Y");
        $m = date("m");
        $d = date("d");
        $from = mktime(0, 0, 0, $m, $d, $y)-(24 * 60 * 60)+1;
        $to = mktime(0, 0, 0, $m, $d, $y);
        //echo date('Y-m-d H:i:s',$from).'---'.date('Y-m-d H:i:s',$to);echo "\n";
        if(empty($admin['user_id'])){
            $this->ajaxReturn(array('msg'=>'登录已失效，请重新登录','status'=>0));
        }
        $click_log['admin_id'] = $admin['user_id'];
        $click_log['time'] = time();
        $click_log['type'] = 2;
        $click_res=M('rebate_click_log','','DB_CONFIG1')->add($click_log);
        //$click_res=1;
        if($click_res){
            $return_operation_log_model = M('return_operation_log','','DB_CONFIG1');
            $has = $return_operation_log_model->where(['time' => $to,'type'=>2])->find();
            if(empty($has)){//$has
                $ibs=M('fdhs_set')->field('fdhs_set.account,fdhs_set.money,user.position')
                    ->join('user ON fdhs_set.account=user.user_id','left')->select();
                $ibs_ids=[];
                foreach($ibs as $k => $v){
                    if($v['position']>1){
                        $ibs_ids[]=$v['account'];
                    }
                }
                if(empty($ibs_ids)){$this->ajaxReturn(array('msg'=>'暂无经纪人','status'=>0));}
                $trades=M('user')->field('user_id,user_recommend')->where('user_recommend in ('.implode(',',$ibs_ids).')')->select();
                $trade=[];
                foreach($trades as $k => $v){
                    $trade[]=$v['user_id'];
                    $trades[$k]['fdhs']=0;
                    foreach($ibs as $ke => $va){
                        if($v['user_recommend']==$va['account']){
                            $trades[$k]['fdhs']=$va['money'];
                            $trades[$k]['parent_position']=$va['position'];break;
                        }
                    }
                }
                $reoups2=[];
                $reoups=M('mt4_trades','','DB_CONFIG2')->field('LOGIN,sum(VOLUME)')
                    ->where('(CMD between 0 and 1) and (CLOSE_TIME between \''.date('Y-m-d H:i:s',$from).'\' and \''.date('Y-m-d H:i:s',$to).'\') and (right(SYMBOL,2) <> \'bo\')')->group('LOGIN')->select();
                foreach ($reoups as $k => $v){
                    if(in_array($v['login'],$trade)){
                        //unset($reoups[$k]);
                        $reoups2[$v['login']]=$v;
                    }
                }
                //$reoups=array_merge($reoups);
                if(empty($reoups)){$this->ajaxReturn(array('msg'=>'未找到交易记录','status'=>0));}

                $list=[];//最终发放数据明细
                foreach($trades as $k => $v){
                    $v['money']=0;
                    if(!empty($reoups2[$v['user_id']])){
                        $v['volume']=$reoups2[$v['user_id']]['sum(volume)']/100;
                        $v['money']=($reoups2[$v['user_id']]['sum(volume)']/100)*$v['fdhs'];
                        if(!empty($v['money'])){$list[]=$v;}
                    }
                    /*foreach($reoups as $ke => $va){
                        if($v['user_id']==$va['login']){
                            $v['volume']=$va['sum(volume)']/100;
                            $v['money']=($va['sum(volume)']/100)*$v['fdhs'];break;
                        }
                    }
                    if(!empty($v['money'])){$list[]=$v;}*/
                }
                if(empty($list)){$this->ajaxReturn(array('msg'=>'没有需要发放的外佣数据','status'=>0));}
                $fdhs_debit_log=[];
                $parents=[];
                //print_r($list);die;
                foreach($list as $k => $v){
                    if($v['money']!=0){
                        $v['money']=$v['money']*-1;
                        $request = "action=changebalance&login=".$v['user_id']."&value=".round($v['money'],2)."&comment=COMMISSION ".date("Ymd",strtotime("-1 day"))."\0";
                        $res = mt4_operation($request);
                        parse_str($res,$return);
                        //$return['result']=1;
                        $parents[]=$v['user_recommend'];
                        $fdhs_debit_log[]=array(
                            'login'=>$v['user_id'],
                            'money'=>$v['money'],
                            'volume'=>$v['volume'],
                            'parent'=>$v['user_recommend'],
                            'time'=>$to,
                            'status'=>$return['result']
                        );
                    }
                }
                M('fdhs_debit_log')->addAll($fdhs_debit_log);
                $parents=array_unique($parents);
                $parents=array_merge($parents);
                $finallData=[];//最终发放数据
                foreach($parents as $k => $v){
                    $msg=array('login'=>$v,'money'=>0);
                    foreach($list as $ke => $va){
                        if($v==$va['user_recommend']){
                            $msg['money']+=$va['money'];
                        }
                    }
                    $finallData[]=$msg;
                }
                $rebate_data=[];
                //print_r($finallData);die;
                foreach($finallData as $k => $v){
                    if($v['money']!=0){
                        $request2 = "action=changebalance&login=".$v['login']."&value=".round($v['money'],2)."&comment=CommFDHs#FDHs ".date("Ymd",strtotime("-1 day"))."\0";
                        $res2 = mt4_operation($request2);
                        parse_str($res2,$return2);
                        //$return2['result']=0;
                        $rebate_data[]=array(
                            'code'=>$return2['result'],//状态码
                            'money'=>round($v['money'],2),// 发放的佣金金额
                            'time'=>time(),
                            'payee'=>$v['login'],//收款人
                            'from'=>$from,//从发放时间
                            'type'=>2,//1-返佣，2-外佣
                            'order_num'=>$return2['order'],//订单号
                            'to'=>$to,//到时间
                        );
                    }
                }
                //$rebate_data==记录的返回数据写入rebate_log 表中
                M('rebate_log')->addAll($rebate_data);
                //将执行人记录到数据库return_operation_log表
                $return_operation_log['admin_id'] = $admin['user_id'];
                $return_operation_log['time'] = $to;
                $return_operation_log['type'] = 2;
                $res = M('return_operation_log')->add($return_operation_log);
                if($res){
                    $this->ajaxReturn(array('msg' => '操作成功', 'status' => 1));
                } else {
                    $this->ajaxReturn(array('msg' => '操作失败', 'status' => 0));
                }
            }else {
                $this->ajaxReturn(array('msg' => '今日外佣已发放', 'status' => 0));
            }
        }else{
            $this->ajaxReturn(array('msg' => '操作失败,请重试', 'status' => 0));
        }
    }

    public function fdhsDebitLog(){//外佣扣款记录
        $status=I('status') ? I('status') : 0;
        $login=I('login') ? I('login') : 0;
        $parent=I('parent') ? I('parent') : 0;
        $from=I('from') ? I('from') : 0;
        $to=I('to') ? I('to') : 0;
        $where='';
        if(!empty($status)){
            if($status==1){
                $where.='(status=1) ';
            }else{
                $where.='(status <> 1) ';
            }
            $this->assign('status',$status);
        }
        if(!empty($login)){
            if(empty($where)){
                $where.='(login='.$login.') ';
            }else{
                $where.=' and (login='.$login.') ';
            }
            $this->assign('login',$login);
        }
        if(!empty($parent)){
            if(empty($where)){
                $where.='(parent='.$parent.') ';
            }else{
                $where.=' and (parent='.$parent.') ';
            }
            $this->assign('parent',$parent);
        }
        if(!empty($from) && !empty($to)){
            if(empty($where)){
                $where.='(time between '.strtotime($from).' and '.strtotime($to.' 23:59:59').') ';
            }else{
                $where.=' and (time between '.strtotime($from).' and '.strtotime($to.' 23:59:59').') ';
            }
            $this->assign('from',$from);
            $this->assign('to',$to);
        }
        $model = M('fdhs_debit_log');
        if(empty($where)){
            $count = $model->count();
        }else{
            $count = $model->where($where)->count();
        }
        $Page = new \Think\Page($count,20);
        $Page->parameter['status']=$status;
        $Page->parameter['login']=$login;
        $Page->parameter['parent']=$parent;
        $Page->parameter['from']=$from;
        $Page->parameter['to']=$to;
        $show = $Page->show();
        if(empty($where)){
            $list = $model->field('id,login,money,parent,time,status')->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        }else{
            $list = $model->field('id,login,money,parent,time,status')->where($where)->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        }
        $this->assign('list',$list);
        $this->assign('page',$show);
        $this->display();
    }

    public function fdhsSet(){//外佣账号列表
        $list=M('fdhs_set')->field('id,account,money')->select();
        $this->assign('list',$list);
        $this->display();
    }

    public function deleteFdsh(){//删除外佣账号
        $id=I('post.id') ? I('post.id') : die(json_encode(array('status'=>0,'msg'=>'非法操作')));
        $res=M('fdhs_set')->where(['id'=>$id])->delete();
        if($res){
            $this->ajaxReturn(array('msg' => '操作成功', 'status' => 1));
        }else{
            $this->ajaxReturn(array('msg' => '操作失败', 'status' => 0));
        }
    }

    public function updateFdshView(){//修改外佣账号页面
        $id=I('id');
        $msg=M('fdhs_set')->where(['id'=>$id])->find();
        $this->assign('msg',$msg);
        $this->display();
    }

    public function updateFdsh(){//修改外佣账号
        $id=I('post.id') ? I('post.id') : die(json_encode(array('status'=>0,'msg'=>'非法操作')));
        //$data['account']=I('post.account') ? I('post.account') : die(json_encode(array('status'=>0,'msg'=>'请输入账号')));
        $data['money']=I('post.money') ? I('post.money') : die(json_encode(array('status'=>0,'msg'=>'请输入金额')));
        $res=M('fdhs_set')->where(['id'=>$id])->save($data);
        if($res){
            $this->ajaxReturn(array('msg' => '操作成功', 'status' => 1));
        }else{
            $this->ajaxReturn(array('msg' => '操作失败', 'status' => 0));
        }
    }

    public function addFdshView(){//添加外佣账号页面
        $this->display();
    }

    public function addFdsh(){//添加外佣账号
        $data['account']=I('post.account') ? I('post.account') : die(json_encode(array('status'=>0,'msg'=>'请输入账号')));
        $data['money']=I('post.money') ? I('post.money') : die(json_encode(array('status'=>0,'msg'=>'请输入金额')));
        $model=M('fdhs_set');
        $has=$model->where(['account'=>$data['account']])->find();
        if($has){
            $this->ajaxReturn(array('msg' => '账号已存在', 'status' => 0));
        }
        $res=$model->add($data);
        if($res){
            $this->ajaxReturn(array('msg' => '操作成功', 'status' => 1));
        }else{
            $this->ajaxReturn(array('msg' => '操作失败', 'status' => 0));
        }
    }

    public function bossAccount(){//小时结算-系统账号
        $list=M('settlement_account')->field('settlement_account.*,user.name_zh_cn,user.user_name,user.user_phone,user.user_email')
            ->join('user ON settlement_account.account = user.user_id')->order('settlement_account.id desc')->select();
        $this->assign('list',$list);
        $this->display();
    }

    public function  deleteAccount(){//小时结算-删除账号
        $id=I('post.id') ? I('post.id') : die(json_encode(array('status'=>0,'msg'=>'非法操作')));
        $res=M('settlement_account')->where(['id'=>$id])->delete();
        if($res){
            $this->ajaxReturn(array('msg'=>'操作成功','status'=>1));
        }else{
            $this->ajaxReturn(array('msg'=>'操作失败，请重试','status'=>0));
        }
    }

    public function addAccountView(){//小时结算-添加账号页面
        $this->display();
    }

    public function addAccount(){//小时结算-添加账号
        $data['account']=I('post.account') ? I('post.account') : die(json_encode(array('status'=>0,'msg'=>'非法操作')));
        $data['ascription']=I('post.ascription') ? I('post.ascription') : 0;
        $data['abbreviation']=I('post.abbreviation') ? I('post.abbreviation') : die(json_encode(array('status'=>0,'msg'=>'请输入账户简称')));
        $model=M('settlement_account');
        $has=$model->where(['account'=>$data['account']])->find();
        if(empty($has)){
            if($data['ascription']==0){
                $res=$model->add($data);
                if($res){
                    $this->ajaxReturn(array('msg'=>'操作成功','status'=>1));
                }else{
                    $this->ajaxReturn(array('msg'=>'操作失败，请重试','status'=>0));
                }
            }else{
                $has_ascription=$model->where(['account'=>$data['ascription']])->find();
                if(empty($has_ascription)){
                    $this->ajaxReturn(array('msg'=>'操作失败，请先添加归属账户','status'=>0));
                }else{
                    $res=$model->add($data);
                    if($res){
                        $this->ajaxReturn(array('msg'=>'操作成功','status'=>1));
                    }else{
                        $this->ajaxReturn(array('msg'=>'操作失败，请重试','status'=>0));
                    }
                }
            }
        }else{
            $this->ajaxReturn(array('msg'=>'账户已存在','status'=>0));
        }
    }

    public function updateAccountView(){//小时结算-修改账号页面
        $id=I('id');
        if(empty($id)){
            $this->error('非法操作');
        }
        $msg=M('settlement_account')->where(['id'=>$id])->find();
        $this->assign('msg',$msg);
        $this->display();
    }

    public function updateAccount(){//小时结算-修改账号
        $id=I('post.id') ? I('post.id') : die(json_encode(array('status'=>0,'msg'=>'非法操作')));
        $data['ascription']=I('post.ascription') ? I('post.ascription') : 0;
        $data['abbreviation']=I('post.abbreviation') ? I('post.abbreviation') : die(json_encode(array('status'=>0,'msg'=>'请输入账户简称')));
        $model=M('settlement_account');
        if($data['ascription']==0){
            $res=$model->where(['id'=>$id])->save($data);
            if($res){
                $this->ajaxReturn(array('msg'=>'操作成功','status'=>1));
            }else{
                $this->ajaxReturn(array('msg'=>'操作失败，请重试','status'=>0));
            }
        }else{
            $has_ascription=$model->where(['account'=>$data['ascription']])->find();
            if(empty($has_ascription)){
                $this->ajaxReturn(array('msg'=>'操作失败，请先添加归属账户','status'=>0));
            }else{
                $res=$model->where(['id'=>$id])->save($data);
                if($res){
                    $this->ajaxReturn(array('msg'=>'操作成功','status'=>1));
                }else{
                    $this->ajaxReturn(array('msg'=>'操作失败，请重试','status'=>0));
                }
            }
        }
    }

    public function settlementLog(){//小时结算-结算记录
        $time=I('post.time') ? strtotime(I('post.time').':00:00') : strtotime(date('Y-m-d H').':00:00');
        $f=date('Y-m-d H:i:s',($time-3600+1));//
        $t=date('Y-m-d H:i:s',$time);
        $has_settlement=M('settlement_operation_log')->where(['from'=>$f,'to'=>$t])->find();
        $return_operation_log='';
        if(!empty($has_settlement)){
            $return_operation_log=1;
        }
        $account=I('account') ? I('account') : 0;
        $from=I('from') ? I('from') : 0;
        $to=I('to') ? I('to') : 0;
        $where='';
        if(!empty($account)){
            $where='(account='.$account.') ';
            $this->assign('account',$account);
        }
        if(!empty($from) && !empty($to)){
            if(empty($where)){
                $where='(`from` between \''.$from.'\' and \''.$to.') ';
            }else{
                $where.=' and (`from` between \''.$from.'\' and \''.$to.') ';
            }
            $this->assign('from',$from);
            $this->assign('to',$to);
        }
        $model = M('settlement_log');
        if(empty($where)){
            $count = $model->count();
        }else{
            $count = $model->where($where)->count();
        }
        $Page = new \Think\Page($count,20);
        $Page->parameter['account']=$account;
        $Page->parameter['from']=$from;
        $Page->parameter['to']=$to;
        $show = $Page->show();
        if(empty($where)){
            $list = $model->field('settlement_log.*,settlement_account.abbreviation')
                ->join('settlement_account ON settlement_log.account = settlement_account.account','left')
                ->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        }else{
            $list = $model->field('settlement_log.*,settlement_account.abbreviation')
                ->join('settlement_account ON settlement_log.account = settlement_account.account','left')
                ->where($where)->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        }
        $this->assign('list',$list);
        $this->assign('page',$show);
        $this->assign('return_operation_log',$return_operation_log);
        $this->display();
    }

    public function getParents($data,$uid){//获取最高上线
        foreach ($data as $k => $v){
            if($uid==$v['user_id']){
                if($v['user_recommend']==0){
                    return $v['user_id'];
                }else{
                    return $this->getParents($data,$v['user_recommend']);
                }
            }
        }
    }

    public function settlement(){//小时结算
        $time=I('post.time') ? strtotime(I('post.time').':00:00') : strtotime('2017-11-02 06:00:00');//date('Y-m-d H').':00:00'
        $from=date('Y-m-d H:i:s',($time-3600+1));//上一小时
        $to=date('Y-m-d H:i:s',$time);//本小时整点
        //echo $from.'*****'.$to;die;
        $has_settlement=M('settlement_operation_log')->where(['from'=>$from,'to'=>$to])->find();
        if(!empty($has_settlement)){
            $this->ajaxReturn(array('msg'=>'当前已结算','status'=>0));
        }
        /*查询短期交易量*/
        $reoups=M('mt4_trades','','DB_CONFIG2')->field('LOGIN,sum(VOLUME),sum(PROFIT)')
            ->where('(CMD between 0 and 1) and (CLOSE_TIME between \''.$from.'\' and \''.$to.'\') and (right(SYMBOL,2) = \'bo\')')->group('LOGIN')->select();
        //print_r($reoups);die;
        if(empty($reoups)){
            $this->ajaxReturn(array('msg'=>'当前无交易记录','status'=>0));
        }
        $login_arr=[];//获取加以用户账号
        foreach ($reoups as $k => $v){
            $login_arr[]=$v['login'];
        }
        $userModel=M('user');
        $user_all=$userModel->field('user_id,user_recommend,position')->select();
        $user_transaction=$userModel->where('user_id in ('.implode(',',$login_arr).')')->field('user_id,user_recommend,position')->select();
        $users=[];//获取交易用户的最高上线
        foreach ($user_transaction as $ke => $va){
            if($va['user_recommend']!=0){
                $parent_id=$this->getParents($user_all,$va['user_recommend']);
                if(!empty($parent_id)){
                    $va['parent_id']=$parent_id;
                    $users[]=$va;
                }
            }
        }
        /*将交易量写入数组*/
        foreach ($users as $k1 => $v1){
            $users[$k1]['volume']=0;
            $users[$k1]['profit']=0;
            foreach ($reoups as $k2 => $v2){
                if($v1['user_id']==$v2['login']){
                    $users[$k1]['volume']=intval($v2['sum(volume)']/100);
                    $users[$k1]['profit']=round($v2['sum(profit)'],2);break;
                }
            }
        }
        $settlement_account=M('settlement_account')->field('account,ascription')->select();//获取结算账号
        $account=[];//Boss账户信息
        $user_id=[];//Boss账号
        foreach($settlement_account as $key => $val){
            if($val['ascription']!=0){
                $user_id[]=$val['ascription'];
                $account[$val['ascription']]['child'][]=$val['account'];
            }else{
                $user_id[]=$val['account'];
                $account[$val['account']]['child'][]=$val['account'];
            }
        }
        //查询boss账户余额
        $balance=M('mt4_users','','DB_CONFIG2')->field('LOGIN,BALANCE')->where('LOGIN in ('.implode(',',$user_id).')')->select();
        foreach ($account as $ka => $va){
            /*$request = "action=getaccountbalance&login=".$ka."\0";
            $ret=mt4_operation($request);
            parse_str($ret,$retData);
            $account[$ka]['balance']=$retData['balance'];*/
            foreach($balance as $k => $v){
                if($ka==$v['login']){
                    $account[$ka]['balance']=$v['balance'];break;
                }
            }
            $account[$ka]['volume_all']=0;//下线的总交易量
            $account[$ka]['profit_all']=0;//下线的总收益
            foreach ($va['child'] as $kc => $vc){
                foreach ($users as $kb => $vb){
                    if($vb['parent_id']==$vc){
                        $account[$ka]['volume_all']+=$vb['volume'];
                        $account[$ka]['profit_all']+=$vb['profit'];break;
                    }
                }
            }
            //$account[$ka]['volume_all']=intval($account[$ka]['volume_all']/100);
            $account[$ka]['settlement']=$account[$ka]['volume_all']*0.022;//下线总结算
            $account[$ka]['finall']=($account[$ka]['profit_all']*-1)-($account[$ka]['volume_all']*0.022);//最终获利
        }
        //查看是否有结算返佣//deposit
        $rebate_time_star=strtotime(date("Y-m-d",$time));
        $rebate_time_end=$rebate_time_star+(24*60*60)-1;
        $settlement_rebate=M('settlement_rebate')->field('id,time')->where('time between \''.$rebate_time_star.'\' and \''.$rebate_time_end.'\'')->find();
        if(empty($settlement_rebate)){//未结算返佣
            $week=date('w');
            if($week==1){//如果是周一，则结算周五的交易返佣
                $rebate=M('mt4_trades','','DB_CONFIG2')->field('LOGIN,PROFIT')
                    ->where('(CMD=6) and (CLOSE_TIME between \''.date('Y-m-d H:i:s',$rebate_time_star-(24*60*60*2)).'\' and \''.date('Y-m-d H:i:s',$rebate_time_end-(24*60*60*2)).'\') and (COMMENT like \'CommBo%\')')
                    ->select();
            }else{
                $rebate=M('mt4_trades','','DB_CONFIG2')->field('LOGIN,PROFIT')
                    ->where('(CMD=6) and (CLOSE_TIME between \''.date('Y-m-d H:i:s',$rebate_time_star).'\' and \''.date('Y-m-d H:i:s',$rebate_time_end).'\') and (COMMENT like \'CommBo%\')')
                    ->select();
            }
            $rebate_uid=[];//前一天收到返佣的账号
            foreach ($rebate as $k => $v){
                $rebate_uid[]=$v['login'];
            }
            if(!empty($rebate_uid)){
                $rebate_users=$userModel->where('user_id in ('.implode(',',$rebate_uid).')')->field('user_id,user_recommend,position')->select();
                if(!empty($rebate_users)){
                    $rebate_user_data=[];//解析返佣账户的最高上线
                    foreach ($rebate_users as $ke => $va){
                        if($va['user_recommend']==0){
                            $parent_id=$va['user_id'];
                        }else{
                            $parent_id=$this->getParents($user_all,$va['user_recommend']);
                        }
                        if(!empty($parent_id)){
                            $va['parent_id']=$parent_id;
                            $rebate_user_data[]=$va;
                        }
                    }
                    foreach($rebate_user_data as $a => $b){
                        $rebate_user_data[$a]['profit']=0;
                        foreach($rebate as $a1 => $b1){
                            if($b['user_id']==$b1['login']){
                                $rebate_user_data[$a]['profit']=$b1['profit'];break;
                            }
                        }
                    }
                    $settlement_rebate_account=[];
                    foreach ($account as $ka => $va){
                        $settlement_rebate_account[]=$ka;
                        $account[$ka]['rebate']=0;
                        foreach ($rebate_user_data as $kb => $vb){
                            foreach ($va['child'] as $kc => $vc){
                                if($vb['parent_id']==$vc){
                                    $account[$ka]['rebate']-=$vb['profit'];
                                    //$account[$ka]['finall']-=$vb['profit'];
                                }
                            }
                        }
                    }
                    //将每天的返佣结算记录写入数据库
                    $settlement_rebate_data['account']=implode(';',$settlement_rebate_account);
                    $settlement_rebate_data['time']=time();
                    $res=M('settlement_rebate')->add($settlement_rebate_data);
                    if(!$res){
                        $this->ajaxReturn(array('msg'=>'操作失败，请重试','status'=>0));
                    }
                }
            }
        }
        $has_settlement=M('settlement_operation_log')->where(['from'=>$from,'to'=>$to])->find();
        if(!empty($has_settlement)){
            $this->ajaxReturn(array('msg'=>'当前已结算','status'=>0));
        }
        print_r($account);die;
        $data=[];//结算数据记录
        $settlement_all=0;//总结算金额
        foreach ($account as $k => $v){
            $settlement_all+=$v['settlement'];
            //此处为综合结算，目前无用
            /*$request = "action=bulkchangebalance&logins=".$k."&value=".$v['finall']."&comment=Deposit ".date('YmdH',($time-3600)).'-'.date('H',$time)."\0";
            $req=mt4_operation($request);
            parse_str($req,$return);*/
            //$return['result']=-1;
            if($v['rebate']==0){//没有返佣需要结算时，只需要结算最终金额
                $notes='Deposit';
                if($v['finall']<0){
                    $notes='withdrawal';
                }
                if($v['finall']==0){
                    $return['result']=1;
                }else{
                    /*$request = "action=bulkchangebalance&logins=".$k."&value=".$v['finall']."&comment=".$notes." ".date('YmdH',($time-3600)).'-'.date('H',$time)."\0";
                    $req=mt4_operation($request);
                    parse_str($req,$return);*/
                    $return['result']=1;
                }
            }else{//有返佣需要结算时，要将返佣和结算分开
                $notes='Deposit';
                if($v['finall']<0){
                    $notes='withdrawal';
                }
                if($v['finall']==0){
                    $return['result']=1;
                }else{
                    /*$request = "action=bulkchangebalance&logins=".$k."&value=".$v['finall']."&comment=".$notes." ".date('YmdH',($time-3600)).'-'.date('H',$time)."\0";
                    $req=mt4_operation($request);
                    parse_str($req,$return);*/
                    $return['result']=1;
                }
                $notes1='Deposit bo';
                if($v['rebate']<0){
                    $notes1='withdrawal bo';
                }
                if($v['rebate']==0){
                    $return_rebate['result']=1;
                }else{
                    /*$request_rebate= "action=bulkchangebalance&logins=".$k."&value=".$v['rebate']."&comment=".$notes1." ".date('Ymd',($time-3600))."\0";
                    $req_rebate=mt4_operation($request_rebate);
                    parse_str($req_rebate,$return_rebate);*/
                    $return['result']=1;
                }
                if(($return['result']!=1) && ($return_rebate['result']!=1)){
                    $return['result']=-1000;
                }else if($return_rebate['result']!=1){
                    $return['result']=-100;
                }
            }
            $data[]=array(
                'account'=>$k,
                'volume_all'=>$v['volume_all'],
                'profit_all'=>$v['profit_all'],
                'settlement'=>$v['settlement'],
                'finall'=>$v['finall'],
                'rebate'=>$v['rebate'] ? $v['rebate'] : 0,
                'status'=>$return['result'],
                'from'=>$from,
                'to'=>$to,
                'time'=>time(),
                'other_desc'=>'',
                'other_expenses'=>0,
                'balance'=>$v['balance'],
                'now_balance'=>($v['balance']+$v['finall']+$v['rebate']),
            );
        }
        $res1=M('settlement_log')->addAll($data);//小时结算记录
        //结算总和结算
        $settlementAllAccount=M('settlement_all_account')->field('account')->find();
        $settlement_data['account']=$settlementAllAccount['account'];//2558964
        $settlement_data['from']=$from;
        $settlement_data['to']=$to;
        $settlement_data['settlement']=$settlement_all;
        $settlement_data['time']=time();
        $notes_all='Deposit';
        if($settlement_all<0){
            $notes_all='withdrawal';
        }
        if($settlement_all==0){
            $return_all['result']=1;
        }else{
            /*$request2 = "action=bulkchangebalance&logins=".$settlement_data['account']."&value=".$settlement_all."&comment=".$notes_all." ".date('YmdH',($time-3600)).'-'.date('H',$time)."\0";
            $req2=mt4_operation($request2);
            parse_str($req2,$return_all);*/
            $return_all['result']=1;
        }
        $settlement_data['status']=$return_all['result'];
        M('settlement_all')->add($settlement_data);//结算总和记录
        if($res1){
            $admin=session('admin_user');
            $operation['from']=$from;
            $operation['to']=$to;
            $operation['admin_id']=$admin['user_id'];
            $operation['time']=time();
            $res2=M('settlement_operation_log')->add($operation);//结算操作记录
            if($res2){
                $this->ajaxReturn(array('msg'=>'操作成功','from'=>$from,'to'=>$to,'status'=>1));
            }else{
                $this->ajaxReturn(array('msg'=>'操作成功,操作日志添加失败！！！','from'=>$from,'to'=>$to,'status'=>1));
            }
        }else{
            $this->ajaxReturn(array('msg'=>'操作失败，请重试!!!','status'=>0));
        }
    }

    public function deleteSettlementLog(){//删除结算
        $id=I('post.id') ? I('post.id') : die(json_encode(array('status'=>0,'msg'=>'非法操作')));
        $model=M('settlement_log');
        $msg=$model->where(['id'=>$id])->find();
        $model->startTrans();
        $res=$model->where(['id'=>$id])->delete();
        $time=time();
        if($msg['status']==-100){//返佣失败，只扣总结算
            $notes='Deposit';
            $finall=($msg['finall']+$msg['other_expenses'])*-1;
            if($finall<0){
                $notes='withdrawal';
            }
            if($finall==0){
                $return['result']=1;
            }else{
                $request = "action=bulkchangebalance&logins=".$msg['account']."&value=".$finall."&comment=".$notes." ".date('YmdH',($time-3600)).'-'.date('H',$time)."\0";
                $req=mt4_operation($request);
                parse_str($req,$return);
            }
        }else if($msg['status']==1){
            if($msg['rebate']==0){//没有返佣，只扣总结算
                $notes='Deposit';
                $finall=($msg['finall']+$msg['other_expenses'])*-1;
                if($finall<0){
                    $notes='withdrawal';
                }
                if($finall==0){
                    $return['result']=1;
                }else{
                    $request = "action=bulkchangebalance&logins=".$msg['account']."&value=".$finall."&comment=".$notes." ".date('YmdH',($time-3600)).'-'.date('H',$time)."\0";
                    $req=mt4_operation($request);
                    parse_str($req,$return);
                }
                $return2['result']=1;
            }else{//有返佣，两者都扣
                $notes='Deposit';
                $finall=($msg['finall']+$msg['other_expenses'])*-1;
                if($finall<0){
                    $notes='withdrawal';
                }
                if($finall==0){
                    $return['result']=1;
                }else{
                    $request = "action=bulkchangebalance&logins=".$msg['account']."&value=".$finall."&comment=".$notes." ".date('YmdH',($time-3600)).'-'.date('H',$time)."\0";
                    $req=mt4_operation($request);
                    parse_str($req,$return);
                }
                $notes_rebate='Deposit bo';
                $finall_rebate=$msg['rebate']*-1;
                if($finall_rebate<0){
                    $notes_rebate='withdrawal bo';
                }
                if($finall_rebate==0){
                    $return2['result']=1;
                }else{
                    $request2 = "action=bulkchangebalance&logins=".$msg['account']."&value=".$finall_rebate."&comment=".$notes_rebate." ".date('Ymd',($time-3600))."\0";
                    $req2=mt4_operation($request2);
                    parse_str($req2,$return2);
                }
            }
        }
        if($return['result']==1){
            $model->commit();
            if($return2['result']==1){
                $this->ajaxReturn(array('msg'=>'操成功作','status'=>1));
            }else{//返佣扣除失败时，记录到返佣补缺
                $rebate['account']=$msg['account'];
                $rebate['rebate']=$finall_rebate;
                $rebate['time']=time();
                $res2=M('settlement_rebate_vacancy')->add($rebate);
                $this->ajaxReturn(array('msg'=>'操成功作,返佣更改失败请手动更改','status'=>-1));
            }
        }else{
            $model->rollback();
            $this->ajaxReturn(array('msg'=>'操作失败','status'=>0));
        }
    }

    public function updateSettlement(){//结算失败重新结算
        $id=I('post.id') ? I('post.id') : die(json_encode(array('status'=>0,'msg'=>'非法操作')));
        $model=M('settlement_log');
        $msg=$model->where(['id'=>$id])->find();
        $from=date('YmdH',strtotime($msg['from']));
        $from2=date('Ymd',strtotime($msg['from']));
        $to=date('H',strtotime($msg['to']));
        /*$request = "action=bulkchangebalance&logins=".$msg['account']."&value=".$msg['finall']."&comment=Deposit ".$from.'-'.$to."\0";
        $req=mt4_operation($request);
        parse_str($req,$return);*/
        if($msg['status']==-1000){//返佣和结算都失败的情况
            $notes='Deposit';
            if($msg['finall']<0){
                $notes='withdrawal';
            }
            if($msg['finall']==0){
                $return['result']=1;
            }else{
                $request = "action=bulkchangebalance&logins=".$msg['account']."&value=".$msg['finall']."&comment=".$notes." ".$from.'-'.$to."\0";
                $req=mt4_operation($request);
                parse_str($req,$return);
            }
            $notes1='Deposit bo';
            if($msg['rebate']<0){
                $notes1='withdrawal bo';
            }
            if($msg['rebate']==0){
                $return_rebate['result']=1;
            }else{
                $request_rebate = "action=bulkchangebalance&logins=".$msg['account']."&value=".$msg['rebate']."&comment=".$notes1." ".$from2."\0";
                $req_rebate=mt4_operation($request_rebate);
                parse_str($req_rebate,$return_rebate);
            }
            if(($return['result']!=1) && ($return_rebate['result']!=1)){
                $return['result']=-1000;
            }else if($return_rebate['result']!=1){
                $return['result']=-100;
            }
        }else if($msg['status']==-100){//返佣结算失败的情况
            $notes='DepositBo';
            if($msg['rebate']<0){
                $notes='withdrawalBo';
            }
            if($msg['rebate']==0){
                $return['result']=1;
            }else{
                $request = "action=bulkchangebalance&logins=".$msg['account']."&value=".$msg['rebate']."&comment=".$notes." ".$from.'-'.$to."\0";
                $req=mt4_operation($request);
                parse_str($req,$return);
            }
        }else{//结算失败的情况
            $notes='Deposit';
            if($msg['finall']<0){
                $notes='withdrawal';
            }
            if($msg['finall']==0){
                $return['result']=1;
            }else{
                $request = "action=bulkchangebalance&logins=".$msg['account']."&value=".$msg['finall']."&comment=".$notes." ".$from.'-'.$to."\0";
                $req=mt4_operation($request);
                parse_str($req,$return);
            }
        }
        if($return['result']==1){
            $model->where(['id'=>$id])->save(['status'=>$return['result']]);
            $this->ajaxReturn(array('msg'=>'操作成功','status'=>1));
        }else{
            $this->ajaxReturn(array('msg'=>'操作失败，请重试','status'=>0));
        }
    }

    public function downloadTransaction(){//结算明细下载
        $id=I('id');
        if(empty($id)){
            $this->error('非法操作');
        }
        $msg=M('settlement_log')->field('account,from,to')->where(['id'=>$id])->find();
        $account=M('settlement_account')->where('(account='.$msg['account'].') or (ascription='.$msg['account'].')')->select();
        $reoups=M('mt4_trades','','DB_CONFIG2')
            ->field('TICKET,LOGIN,OPEN_TIME,OPEN_PRICE,CMD,SYMBOL,VOLUME,CLOSE_TIME,CLOSE_PRICE,COMMENT,PROFIT')//2558964
            ->where('(CMD between 0 and 1) and (CLOSE_TIME between \''.$msg['from'].'\' and \''.$msg['to'].'\')')->select();
        if(empty($reoups)){
            $this->error('该时段无交易');
        }
        $login_arr=[];
        foreach ($reoups as $k => $v){
            $login_arr[]=$v['login'];
        }
        $login_arr=array_unique($login_arr);
        $login_arr=array_merge($login_arr);
        $userModel=M('user');
        $user_all=$userModel->field('user_id,user_recommend,position')->select();
        //$user_transaction=$userModel->where('user_id in ('.implode(',',$login_arr).')')->field('user_id,user_recommend,position')->select();
        $user_transaction=[];
        foreach ($user_all as $k => $v){
            foreach ($login_arr as $ke => $va){
                if($v['user_id']){
                    $user_transaction[]=$k;break;
                }
            }
        }
        $users=[];
        foreach ($user_transaction as $ke => $va){
            $parent_id=$this->getParents($user_all,$va['user_recommend']);
            if(!empty($parent_id)){
                $va['parent_id']=$parent_id;
                $users[]=$va;
            }
        }
        $list=[];
        foreach ($reoups as $k1 => $v1){
            foreach ($users as $k2 => $v2){
                if($v1['login']==$v2['user_id']){
                    $v1['parent_id']=$v2['parent_id'];
                    $list[]=$v1;break;
                }
            }
        }
        $data=[];
        foreach ($account as $k => $v){
            foreach ($list as $ke => $va){
                if($v['account']==$va['parent_id']){
                    $va['volume']=intval($va['volume']/100);
                    if($va['cmd']==1){
                        $va['cmd']='sell';
                    }else{
                        $va['cmd']='buy';
                    }
                    $va['parent_id']=$msg['account'];
                    $data[]=$va;
                }
            }
        }
        //print_r($data);die;
        $csv=new \Think\Csv();
        $csv_title=array('TICKET','LOGIN','OPEN_TIME','OPEN_PRICE','TYPE','SYMBOL','VOLUME','CLOSE_TIME','CLOSE_PRICE','COMMENT','PROFIT','IB');
        $csv->put_csv($data,$csv_title);
    }

    public function downloadAll(){//结算记录下载
        $account=I('account') ? I('account') : 0;
        $from=I('from') ? I('from') : 0;
        $to=I('to') ? I('to') : 0;
        $model = M('settlement_log');
        $where='';
        if(!empty($account)){
            $where='(account='.$account.') ';
        }
        if(!empty($from) && !empty($to)){
            if(empty($where)){
                $where='(`from` between \''.$from.'\' and \''.$to.' 23:59:59) ';
            }else{
                $where.=' and (`from` between \''.$from.'\' and \''.$to.' 23:59:59) ';
            }
        }
        /*$list = $model
            ->field('settlement_account.abbreviation,settlement_log.from,settlement_log.to,settlement_log.account,settlement_log.volume_all,settlement_log.settlement,settlement_log.profit_all,settlement_log.rebate,settlement_log.other_desc,settlement_log.other_expenses,settlement_log.finall,settlement_log.now_balance,settlement_log.status,settlement_log.time')
            ->join('settlement_account ON settlement_log.account = settlement_account.account','left')->order('id desc')->select();*/
        if(empty($where)){
            $list = $model->field('`from`,`to`,account,volume_all,settlement,profit_all,rebate,other_desc,other_expenses,`finall`,now_balance,status,time')
                ->order('id desc')->select();
        }else{
            $list = $model->field('`from`,`to`,account,volume_all,settlement,profit_all,rebate,other_desc,other_expenses,`finall`,now_balance,status,time')
                ->where($where)->order('id desc')->select();
        }
        $msg=[];
        foreach ($list as $k => $v){
            $msg[]=array(
                //'name'=>$v['abbreviation'],
                'from'=>$v['from'],
                'to'=>$v['to'],
                'account'=>$v['account'],//.' ('.$v['abbreviation'].')',
                //'balance'=>$v['balance'],
                'volume_all'=>$v['volume_all'],
                'settlement'=>$v['settlement'],
                'profit_all'=>$v['profit_all'],
                'rebate'=>$v['rebate'],
                'other_expenses'=>$v['other_desc'].' : '.$v['other_expenses'],
                'finall'=>$v['finall'],
                'now_balance'=>$v['now_balance'],
                'status'=>$v['status'],
                'time'=>date('Y-m-d H:i:s',$v['time'])
            );
        }
        $csv=new \Think\Csv();
        $csv_title=array('开始时间','结束时间','账号','用户总投资','结算2.2%','用户实际收益','IB返佣','其他费用','结算对冲','现余额','状态','执行时间');
        $csv->put_csv($msg,$csv_title);
    }

    public function otherExpensesView(){//小时结算-添加其他费用界面
        $id=I('id');
        if(empty($id)){
            $this->error('非法操作');
        }
        $msg=M('settlement_log')->where(['id'=>$id])->find();
        $this->assign('msg',$msg);
        $this->display();
    }

    public function otherExpenses(){//添加其他费用
        $id=I('post.id') ? I('post.id') : die(json_encode(array('status'=>0,'msg'=>'非法操作')));
        $data['other_desc']=I('post.other_desc') ? I('post.other_desc') : '';
        $data['other_expenses']=I('post.other_expenses') ? I('post.other_expenses') : die(json_encode(array('status'=>0,'msg'=>'金额不正确')));
        if(empty($id)){
            $this->ajaxReturn(array('msg'=>'非法操作','status'=>0));
        }
        $model=M('settlement_log');
        $msg=$model->where(['id'=>$id])->find();
        $data['now_balance']=$data['other_expenses']+$msg['now_balance'];
        $time=time();
        $model->startTrans();
        $res=$model->where(['id'=>$id])->save($data);
        if($res){
            $notes='Deposit';
            if($data['other_expenses']<0){
                $notes='withdrawal';
            }
            /*$request = "action=bulkchangebalance&logins=".$msg['account']."&value=".$data['other_expenses']."&comment=".$notes." ".date('YmdH',($time-3600)).'-'.date('H',$time)."\0";
            $req=mt4_operation($request);
            parse_str($req,$return);*/
            $return['result']=1;
            if($return['result']==1){
                $model->commit();
                $this->ajaxReturn(array('msg'=>'操成功作','status'=>1));
            }else{
                $model->rollback();
                $this->ajaxReturn(array('msg'=>'操作失败','status'=>0));
            }
        }else{
            $model->rollback();
            $this->ajaxReturn(array('msg'=>'操作失败,请重试','status'=>0));
        }
    }

    public function settlementAll(){//小时结算-结算总览
        $from=I('post.from') ? I('post.from') : 0;
        $to=I('post.to') ? I('post.to') : 0;
        $model = M('settlement_all');
        if(empty($from) || empty($to)){
            $count=$model->count();
        }else{
            $count=$model->where('time between '.strtotime($from).' and '.strtotime($to.' 23:59:59'))->count();
        }
        $page= new \Think\Page($count,20);
        $show= $page->show();
        $page->parameter['from']=$from;
        $page->parameter['to']=$to;
        if(empty($from) || empty($to)){
            $list = $model->field('*')->order('id desc')->limit($page->firstRow.','.$page->listRows)->select();
        }else{
            $list = $model->field('*')->where('time between '.strtotime($from).' and '.strtotime($to.' 23:59:59'))
                ->order('id desc')->limit($page->firstRow.','.$page->listRows)->select();
            $this->assign('from',$from);
            $this->assign('to',$to);
        }
        $this->assign('list',$list);
        $this->assign('page',$show);
        $this->display();
    }

    public function update_settlement_all(){//汇总失败，重返
        $id=I('post.id') ? I('post.id') : die(json_encode(array('status'=>0,'msg'=>'非法操作')));
        $model=M('settlement_all');
        $msg=$model->where(['id'=>$id])->find();
        $model->startTrans();
        $res=$model->where(['id'=>$id])->save(['status'=>1]);
        if($res){
            $from=date('YmdH',strtotime($msg['from']));
            $to=date('H',strtotime($msg['to']));
            $notes='Deposit';
            if($msg['settlement']<0){
                $notes='withdrawal';
            }
            if($msg['settlement']==0){
                $return['result']=1;
            }else{
                $request = "action=bulkchangebalance&logins=".$msg['account']."&value=".$msg['settlement']."&comment=".$notes." ".$from.'-'.$to."\0";
                $req=mt4_operation($request);
                parse_str($req,$return);
            }
            if($return['result']==1){
                $model->commit();
                $this->ajaxReturn(array('msg'=>'操作成功','status'=>1));
            }else{
                $model->rollback();
                $this->ajaxReturn(array('msg'=>'操作失败','status'=>0));
            }
        }else{
            $this->ajaxReturn(array('msg'=>'操作失败，请重试','status'=>0));
        }
    }

    public function deleteSettlementAll(){//删除汇总
        $id=I('post.id') ? I('post.id') : die(json_encode(array('status'=>0,'msg'=>'非法操作')));
        $model=M('settlement_all');
        $msg=$model->where(['id'=>$id])->find();
        $money=$msg['settlement']*-1;
        $from=date('YmdH',strtotime($msg['from']));
        $to=date('H',strtotime($msg['to']));
        $res=$model->where(['id'=>$id])->delete();
        if($res){
            if($msg['status']==1){
                $data['account']=$msg['account'];
                $data['type']=2;
                $data['money']=$money;
                $request = "action=bulkchangebalance&logins=".$msg['account']."&value=".$money."&comment=withdrawal ".$from.'-'.$to."\0";
                $req=mt4_operation($request);
                parse_str($req,$return);
                if($return['result']==1){
                    $data['status']=$return['result'];
                    $res2=$model->add($data);
                    if($res2){
                        $this->ajaxReturn(array('msg'=>'操作成功','status'=>1));
                    }else{
                        $this->ajaxReturn(array('msg'=>'操作成功,记录未添加','status'=>-1));
                    }
                }else{
                    $this->ajaxReturn(array('msg'=>'操作失败，请重试','status'=>0));
                }
            }else{
                $this->ajaxReturn(array('msg'=>'操作成功','status'=>1));
            }
        }else{
            $this->ajaxReturn(array('msg'=>'操作失败','status'=>0));
        }
    }
}